import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { NzModalRef, NzMessageService, NzNotificationService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFUISchema } from '@delon/form';
import { Observable, of, zip } from 'rxjs';
import { catchError } from 'rxjs/operators';

/**
 * 字典添加/
 */
@Component({
  selector: 'app-sysparam-edit',
  templateUrl: './sysparam-edit.component.html',
})
export class SysParamEditComponent implements OnInit {
  paramTypes = [];
  dictTypes = [];
  statusTypes = [];

  @Input()
  record: any = {};
  i: any;
  schema: SFSchema = {
    properties: {},
  };
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 100,
      grid: { span: 12 },
    },
  };

  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    private notice: NzNotificationService,
  ) {}

  ngOnInit(): void {
    const api = [
      this.http.get(`/cf/admin/dict/type/status_type`),
      this.http.get(`/cf/admin/dict/type/dict_type`),
      this.http.get(`/cf/admin/dict/type/param_type`),
    ];
    zip(...api)
      .pipe(
        catchError(([statusType, dictType, paramType]) => {
          return [statusType, dictType, paramType];
        }),
      )
      .subscribe(([statusType, dictType, paramType]) => {
        this.statusTypes = statusType.data;
        this.dictTypes = dictType.data;
        this.paramTypes = paramType.data;
        this.buildSf();
        if (this.record.id) {
          this.http.get(`/cf/admin/param/${this.record.id}`).subscribe(res => (this.i = res.data));
        }
      });
  }

  buildSf() {
    this.schema = {
      properties: {
        name: { type: 'string', title: '名称' },
        key: { type: 'string', title: '键' },
        value: { type: 'string', title: '值' },
        status: {
          type: 'string',
          title: '状态',
          enum: this.statusTypes,
        },
        publicType: { type: 'string', title: '类型', enum: this.paramTypes },
      },
      required: ['key', 'value', 'publicType'],
    };
  }

  save(value: any) {
    value.key = value.key.toUpperCase();
    const req: Observable<string> = this.record.id
      ? this.http.put('/cf/admin/param', value)
      : this.http.post(`/cf/admin/param`, value);

    req.pipe(catchError(err => of(err))).subscribe(res => {
      if (res.status === 200) {
        this.notice.success('成功', '保存成功');
        this.modal.close(true);
      }
    });
  }

  close() {
    this.modal.destroy();
  }
}
